package com.zzy.system.service.impl;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zzy.common.core.redis.RedisCache;
import com.zzy.common.utils.guanmai.GuanmaiCommon;
import com.zzy.system.domain.*;
import com.zzy.system.mapper.*;
import com.zzy.system.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class GuanmaiBaseInfoServiceImpl implements IGuanmaiBaseInfoService {

    private static final Logger log = LoggerFactory.getLogger(GuanmaiBaseInfoServiceImpl.class);

    // 注入 RedisCache 对象
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IGuanmaiSkuService iGuanmaiSkuService;

    @Autowired
    private IGuanmaiSpuService iGuanmaiSpuService;

    @Autowired
    private IGuanmaiCustomerService iGuanmaiCustomerService;

    @Autowired
    private IGuanmaiCustomerItemService guanmaiCustomerItemService;

    @Autowired
    private GuanmaiSupplierMapper guanmaiSupplierMapper;
    @Autowired
    private GuanmaiCustomerMapper guanmaiCustomerMapper;

    @Autowired
    private GuanmaiSpuMapper guanmaiSpuMapper;

    @Autowired
    private IPushDataService pushDataService;



    // 注入配置文件中的观麦令牌在 Redis 中的键名
    @Value("${api.guanmaiTokenKey}")
    private String guanmaiTokenKey;
    @Autowired
    private SysDicCityMapper sysDicCityMapper;
    @Autowired
    private AreaCodeMapper areaCodeMapper;


    @Override
    public String getGuanmaiSku() throws Exception {
        Map<String, Object> paramMap = new HashMap<>();
        //请求观麦 获取订单列表
        String reponse =  GuanmaiCommon.sendRequestGet(paramMap,"/v1/api/product/sku/list/1.0" );
        JSONObject reponseJson = JSONObject.parseObject(reponse);
        if(reponseJson.getInteger("code")==1002){
            redisCache.deleteObject(guanmaiTokenKey);
            GuanmaiCommon.getGuanmaiToken();
            return "";
        }
        if (reponseJson.get("code").toString().equals("0")) {
            JSONArray jsonArray = reponseJson.getJSONArray("data");
            if (jsonArray != null) {
                List<GuanmaiSku> guanmaiSkuList = jsonArray.toJavaList(GuanmaiSku.class);
                iGuanmaiSkuService.saveSkuList(guanmaiSkuList);
            }
        }
        return "";
    }

    @Override
    public String getGuanmaiSupplier() throws Exception {
        QueryWrapper<GuanmaiSupplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("guanmai_supplier_id", 0);
        queryWrapper.isNull("dept_id");
        guanmaiSupplierMapper.delete(queryWrapper);
        List<GuanmaiSupplier> allgGuanmaiSupplierList = new ArrayList<>();
        Integer limit=100;
        Integer offset=0;
        while(true){
            Map<String, Object> paramMap = new HashMap<>();
            //paramMap.put("category2_id", categoryId);
            paramMap.put("limit", limit);
            paramMap.put("offset", offset);
            //请求观麦 获取订单列表
            String reponse = GuanmaiCommon.sendRequestGet(paramMap, "/v1/api/stock/supplier/list/1.0");
            JSONObject reponseJson = JSONObject.parseObject(reponse);
            if (reponseJson.get("code").toString().equals("0")) {
                JSONArray jsonArray = reponseJson.getJSONArray("data");
                if (jsonArray != null) {
                    // 将当前页的数据解析并添加到总的结果列表中
                    List<GuanmaiSupplier> guanmaiSupplier = jsonArray.toJavaList(GuanmaiSupplier.class);
                    allgGuanmaiSupplierList.addAll(guanmaiSupplier);
                    // 如果返回的数据条数等于每页显示的数量，说明可能还有更多数据，继续查询下一页
                    if (jsonArray.size() == limit) {
                        offset += limit; // 页码增加，指向下一页
                        continue;
                    }else{
                        break;
                    }
                }
            }
        }
        QueryWrapper<SysDicCity> sysDicCityQueryWrapper = new QueryWrapper<>();
        sysDicCityQueryWrapper.eq("level","40");
        List<SysDicCity>sysDicCityList=sysDicCityMapper.selectList(sysDicCityQueryWrapper);

        QueryWrapper<AreaCode> areaCodeQueryWrapper = new QueryWrapper<>();
        areaCodeQueryWrapper.eq("level","3");
        List<AreaCode>areaCodeList=areaCodeMapper.selectList(areaCodeQueryWrapper);

        int batchSize = 100;
        for (int i = 0; i < allgGuanmaiSupplierList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, allgGuanmaiSupplierList.size());
            List<GuanmaiSupplier> batchList = allgGuanmaiSupplierList.subList(i, endIndex);
            // 这里可以将batchList用于实际的saveBatch操作或者其他处理
            System.out.println("当前批次数据量: " + batchList.size());
            batchInsertSupplier(batchList,batchSize,sysDicCityList,areaCodeList);
        }

        return "";
    }
    public void batchInsertSupplier(List<GuanmaiSupplier> guanmaiSupplierList, int batchSize, List<SysDicCity> sysDicCityList, List<AreaCode>areaCodeList) throws Exception {
        // 提前查询数据库中已存在的Orderid集合
        List<String> existingSheetIds = getExistingSupplierIds(guanmaiSupplierList);
        // 过滤掉已存在的orderId对应的记录
        List<GuanmaiSupplier> filteredList = filterExistingSupplier(guanmaiSupplierList, existingSheetIds);
        // 按批次插入过滤后的数据
        for (int i = 0; i < filteredList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, filteredList.size());
            List<GuanmaiSupplier> batchList = filteredList.subList(i, endIndex);
            System.out.println("当前批次数据量: " + batchList.size());
            for (GuanmaiSupplier guanmaiSupplier : batchList) {
                //请求观麦 获取订单列表
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("supplier_id", guanmaiSupplier.getSupplierId());
                String reponse = GuanmaiCommon.sendRequestGet(paramMap, "/v1/api/stock/supplier/get/1.0");
                JSONObject reponseJson = JSONObject.parseObject(reponse);
                if (reponseJson.getInteger("code") == 1002) {
                    redisCache.deleteObject(guanmaiTokenKey);
                    GuanmaiCommon.getGuanmaiToken();
                }
                if (reponseJson.get("code").toString().equals("0")) {
                    JSONObject jsonObject = reponseJson.getJSONObject("data");
                    if (jsonObject != null) {
                        GuanmaiSupplier guanmaiSupplier1=jsonObject.toJavaObject(GuanmaiSupplier.class);
                        //如果地址为空  结束循环
                        if(guanmaiSupplier1.getCompanyAddress()==null){
                            continue;
                        }
                        // 根据供应商地址匹配区县id
                        SysDicCity sysDicCity = FilterSysDicCityBySupplier(sysDicCityList,guanmaiSupplier1.getCompanyAddress());
                        //匹配重庆市外的区县地址
                        AreaCode areaCode=FilterAreaCodeBySupplier(areaCodeList,guanmaiSupplier1.getCompanyAddress());
                        if(sysDicCity!=null){
                            guanmaiSupplier1.setAreaCode(sysDicCity.getDicAreaCode());
                        }else{
                            if(areaCode!=null){
                                guanmaiSupplier1.setAreaCode(areaCode.getCode());
                            }
                        }
                        guanmaiSupplierMapper.insert(guanmaiSupplier1);
                        if(sysDicCity!=null||areaCode!=null){
                            pushDataService.getChongqingSupplier(guanmaiSupplier1);
                            //如果供应商已经新增了 并且溯源id不为空 那么就可以结束循环了
                            if(guanmaiSupplier1.getDeptId()!=null){
                                continue;
                            }
                            if(sysDicCity!=null){
                                guanmaiSupplier1.setAreaCode(sysDicCity.getDicAreaCode());
                                pushDataService.pushSupplier(guanmaiSupplier1);

                            }else if(areaCode!=null){
                                guanmaiSupplier1.setAreaCode(areaCode.getCode());
                                pushDataService.pushSupplier(guanmaiSupplier1);
                            }

                        }
                    }

                }
            }
        }
    }
    public static SysDicCity FilterSysDicCityBySupplier(List<SysDicCity> sysDicCityList, String supplierArea) {
        // 检查列表是否为空或 supplierId 是否为 null
        if (sysDicCityList == null || sysDicCityList.isEmpty() || supplierArea == null) {
            return null;
        }
        // 使用 Stream API 进行筛选操作
        Optional<SysDicCity> firstMatch = sysDicCityList.stream()
                // 通过 supplierId 进行条件匹配
                .filter(sysDicCity -> supplierArea.equals(sysDicCity.getShortName()) || supplierArea.equals(sysDicCity.getFullShortName()))
                // 查找第一个匹配的元素
                .findFirst();
        // 如果存在匹配的元素，返回该元素，否则返回 null
        return firstMatch.orElse(null);
    }
    public static AreaCode FilterAreaCodeBySupplier(List<AreaCode> areaCodeList, String supplierArea) {
        // 检查列表是否为空或 supplierId 是否为 null
        if (areaCodeList == null || areaCodeList.isEmpty() || supplierArea == null) {
            return null;
        }
        // 使用 Stream API 进行筛选操作
        Optional<AreaCode> firstMatch = areaCodeList.stream()
                // 通过 supplierId 进行条件匹配
                .filter(areaCode -> supplierArea.equals(areaCode.getName()))
                // 查找第一个匹配的元素
                .findFirst();
        // 如果存在匹配的元素，返回该元素，否则返回 null
        return firstMatch.orElse(null);
    }
    private List<String> getExistingSupplierIds(List<GuanmaiSupplier> guanmaiSupplierList) {
        if (guanmaiSupplierList == null || guanmaiSupplierList.isEmpty()) {
            return new ArrayList<>();
        }

        List<String> sheetIdList = new ArrayList<>();
        for (GuanmaiSupplier guanmaiSupplier : guanmaiSupplierList) {
            sheetIdList.add(guanmaiSupplier.getSupplierId());
        }

        QueryWrapper<GuanmaiSupplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("supplier_id").in("supplier_id", sheetIdList);

        return this.guanmaiSupplierMapper.selectObjs(queryWrapper).stream()
                .map(obj -> (String) obj).collect(Collectors.toList());
    }
    private List<GuanmaiSupplier> filterExistingSupplier(List<GuanmaiSupplier> guanmaiSupplierList, List<String> existingSheetIds) {
        List<GuanmaiSupplier> guanmaiSuppliers = new ArrayList<>();
        for (GuanmaiSupplier guanmaiSupplier : guanmaiSupplierList) {
            if (!existingSheetIds.contains(guanmaiSupplier.getSupplierId())) {
                guanmaiSuppliers.add(guanmaiSupplier);
            }
        }
        return guanmaiSuppliers;
    }
    @Override
    public String getGuanmaiCustomer() throws Exception {
        QueryWrapper<GuanmaiCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("guanmai_customer_id", 0);
        guanmaiCustomerMapper.delete(queryWrapper);
        int offset = 0;
        int limit = 100;
        List<GuanmaiCustomer> allGuanmaiCustomerList = new ArrayList<>();
        while (true) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("offset", offset);
            paramMap.put("limit", limit);
            //请求观麦 获取订单列表
            String reponse = GuanmaiCommon.sendRequestGet(paramMap, "/v1/api/customer/list/1.0");
            JSONObject reponseJson = JSONObject.parseObject(reponse);
            if (reponseJson.getInteger("code") == 1002) {
                redisCache.deleteObject(guanmaiTokenKey);
                GuanmaiCommon.getGuanmaiToken();
                return "";
            }
            if (reponseJson.get("code").toString().equals("0")) {
                JSONArray jsonArray = reponseJson.getJSONArray("data");
                if (jsonArray != null) {
                    List<GuanmaiCustomer> guanmaiCustomerList = jsonArray.toJavaList(GuanmaiCustomer.class);
                    allGuanmaiCustomerList.addAll(guanmaiCustomerList);
                    if (jsonArray.size() == limit) {
                        offset += limit; // 页码增加，指向下一页
                        continue;
                    } else {
                        // 如果返回的数据条数小于每页显示的数量，说明已经查询完所有数据，结束循环
                        break;
                    }
                }
            }
        }
        int batchSize = 100;
        for (int i = 0; i < allGuanmaiCustomerList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, allGuanmaiCustomerList.size());
            List<GuanmaiCustomer> batchList = allGuanmaiCustomerList.subList(i, endIndex);
            // 这里可以将batchList用于实际的saveBatch操作或者其他处理
            System.out.println("当前批次数据量: " + batchList.size());
            iGuanmaiCustomerService.saveCustomerList(batchList);
        }
        for(GuanmaiCustomer guanmaiCustomer : allGuanmaiCustomerList){
            getGuanmaiCustomerItem(guanmaiCustomer.getCustomerId());

        }
        return "";
    }

    @Override
    public String getGuanmaiCustomerItem(String customerId) throws Exception {

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", customerId);
        //请求观麦 获取商户详情
        String reponse = GuanmaiCommon.sendRequestGet(paramMap,"/v1/api/customer/get/1.0" );
        JSONObject reponseJson = JSONObject.parseObject(reponse);
        if (reponseJson.get("code").toString().equals("0")) {
            JSONObject jsonObject = reponseJson.getJSONObject("data");
            if (jsonObject != null) {
                // 将当前页的数据解析并添加到总的结果列表中
                GuanmaiCustomerItem guanmaiCustomerItem = JSON.parseObject(jsonObject.toString(), GuanmaiCustomerItem.class);
                guanmaiCustomerItemService.saveCustomerItemList(guanmaiCustomerItem);


            }
        }
        return "";
    }

    @Override
    public String getGuanmaiSpu() throws Exception {
        QueryWrapper<GuanmaiSpu> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("guanmai_spu_id", 0);
        queryWrapper.eq("is_push", 0);

        guanmaiSpuMapper.delete(queryWrapper);
        int offset = 0;
        int limit = 100;
        List<GuanmaiSpu> allGuanmaiSpuList = new ArrayList<>();
        while (true) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("offset", offset);
            paramMap.put("limit", limit);
            paramMap.put("category1_id", "A69776");
            //请求观麦 获取订单列表
            String reponse = GuanmaiCommon.sendRequestGet(paramMap, "/v1/api/product/spu/list/1.0");
            JSONObject reponseJson = JSONObject.parseObject(reponse);
            if (reponseJson.getInteger("code") == 1002) {
                redisCache.deleteObject(guanmaiTokenKey);
                GuanmaiCommon.getGuanmaiToken();
                return "";
            }

            if (reponseJson.get("code").toString().equals("0")) {
                JSONArray jsonArray = reponseJson.getJSONArray("data");
                if (jsonArray != null) {
                    List<GuanmaiSpu> guanmaiSpuList = jsonArray.toJavaList(GuanmaiSpu.class);
                    allGuanmaiSpuList.addAll(guanmaiSpuList);
                    // 如果返回的数据条数等于每页显示的数量，说明可能还有更多数据，继续查询下一页
                    if (jsonArray.size() == limit) {
                        offset += limit; // 页码增加，指向下一页
                        continue;
                    } else {
                        // 如果返回的数据条数小于每页显示的数量，说明已经查询完所有数据，结束循环
                        break;
                    }
                }
            }
        }
        int batchSize = 200;
        for (int i = 0; i < allGuanmaiSpuList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, allGuanmaiSpuList.size());
            List<GuanmaiSpu> batchList = allGuanmaiSpuList.subList(i, endIndex);
            // 这里可以将batchList用于实际的saveBatch操作或者其他处理
            System.out.println("当前批次数据量: " + batchList.size());
            for(GuanmaiSpu guanmaiSpu : batchList){
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("spu_id", guanmaiSpu.getSpuId());
                //请求观麦 获取订单列表
                String reponse = GuanmaiCommon.sendRequestGet(paramMap, "/v1/api/product/spu/get/1.0");
                JSONObject reponseJson = JSONObject.parseObject(reponse);
                if (reponseJson.getInteger("code") == 1002) {
                    redisCache.deleteObject(guanmaiTokenKey);
                    GuanmaiCommon.getGuanmaiToken();
                    return "";
                }
                if (reponseJson.get("code").toString().equals("0")) {
                    JSONObject jsonObject = reponseJson.getJSONObject("data");
                    GuanmaiSpu guanmaiSpu1 = JSON.parseObject(jsonObject.toString(), GuanmaiSpu.class);
                    if (guanmaiSpu1 != null&&!guanmaiSpu1.getImages().isEmpty()) {
                        ;
                        guanmaiSpu1.setImagePath(guanmaiSpu1.getImages().stream()
                                .collect(Collectors.joining(",")));
                    }
                    iGuanmaiSpuService.saveSpu(guanmaiSpu1);
                }
            }
        }
        return "";
    }


}